package com.lst.tools.basics.factory;

import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.springframework.boot.env.PropertySourcesLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;

/**
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
public class CustomYmlPropertyFactory implements PropertySourceFactory {

    private static String getNameForResource(Resource resource) {
        String name = resource.getDescription();
        if (StringUtils.isNotBlank(name)) {
            return name;
        }
        return resource.getClass().getSimpleName() + "@" + System.identityHashCode(resource);
    }

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
        Resource resource = encodedResource.getResource();
        if (name != null) {
            return new PropertySourcesLoader().load(resource, name, null);
        } else {
            return new PropertySourcesLoader().load(resource, getNameForResource(resource), null);
        }
    }
}
